<template>
  <div class="book-list">
    <p class="title">BookList</p>
    <div class="book">
      <span class="ordinal">序号</span>
      <span class="name">书名</span>
      <span class="price">定价</span>
      <span class="publisher">出版单位</span>
      <span class="date">出版时间</span>
      <span class="author">作者</span>
      <span class="operation" v-if="$root.logged"></span>
    </div>
    <div class="book" v-for="(b,i) in books" :key="b.id" >
      <span class="ordinal">{{ i + 1 }}</span>
      <span class="name">{{ b.name }}</span>
      <span class="price">{{ b.price }}</span>
      <span class="publisher">{{ b.publisher }}</span>
      <span class="date">{{ b.pubDate }}</span>
      <span class="author">{{ b.author }}</span>
      <span class="operation" v-if="$root.logged">
        <el-button type="primary" size="small" :icon="Edit" @click="update(b.id)"></el-button>
        <el-button type="primary" size="small" :icon="Delete" @click="remove(b.id)"></el-button>
      </span>
    </div>
  </div>
</template>

<script>
export default {
    name: 'BookList'
}
</script>

<script setup>
// 导入函数
import { getCurrentInstance , onBeforeMount , reactive } from 'vue' ;
// 导入 element-plus 的 按钮中使用的 icons
import { Edit, Delete } from '@element-plus/icons-vue' ;
// 从 vue-router 中导入用来获取 Router 的函数
import { useRouter } from 'vue-router' ;

// 获得当前实例(即当前组件对应的实例)
const { proxy } = getCurrentInstance();

//  获得 Router 对象
const router = useRouter();

// 在 setup 中声明的函数可以在 template 中使用
const books = reactive( [ ] );

// 生命周期钩子
onBeforeMount( async () =>{
  let resp = await proxy.$http.get( '/book/list' ) ;
  if( resp.status == 200 ){
    // 将从后端获取到的数组元素添加到 books 数组中
    books.push( ...resp.data );
  }
});

// 在 setup 中声明的函数可以在 template 中调用
function remove(id){
  // 通过 axios 发送异步请求来删除指定的图书
  proxy.$http.get( `/book/remove/${id}` ).then(resp=>{
    if( resp.status == 200 && resp.data.success ) {
      alert( resp.data.message );
      // 删除页面上显示的数据
      let index = books.findIndex( book => book.id == id );
      if( index != null ) {
        books.splice( index , 1 );
      }
    }
  }).catch( error => {
    console.log( error );
  });
}

function update(id) {
  // 编程式导航
  router.push( { name: 'bookEdit' , params: { id: id } } );
}

</script>

<style scoped>

.book-list {
  border: 1px solid #dedede ;
}

.book {
  display: flex ;
  margin: 5px ;
  border-bottom: 1px solid #dedede ;
}

.book>span {
  flex-basis: 100px ; 
  text-align: center ;
  line-height: 40px ;
}

.book>span.name ,
.book>span.publisher {
  flex-basis: 300px ;
}

.book>span.operation {
  flex-basis: 200px ;
}

.book>span.date {
  flex-basis: 150px ;
}

</style>